package org.dromara.common.websocket.listener

import cn.hutool.core.collection.CollUtil
import io.github.oshai.kotlinlogging.KotlinLogging
import org.dromara.common.websocket.dto.WebSocketMessageDto
import org.dromara.common.websocket.holder.WebSocketSessionHolder
import org.dromara.common.websocket.holder.WebSocketSessionHolder.getSessionsAll
import org.dromara.common.websocket.utils.WebSocketUtils.sendMessage
import org.dromara.common.websocket.utils.WebSocketUtils.subscribeMessage
import org.springframework.boot.ApplicationArguments
import org.springframework.boot.ApplicationRunner
import org.springframework.core.Ordered

/**
 * WebSocket 主题订阅监听器
 *
 * @author LikeYouDo
 * @date 2025/09/22
 */
class WebSocketTopicListener : ApplicationRunner, Ordered {
    companion object {
        private val log = KotlinLogging.logger { }
    }

    /**
     * 在Spring Boot应用程序启动时初始化WebSocket主题订阅监听器
     *
     * @param args 应用程序参数
     * @throws Exception 初始化过程中可能抛出的异常
     */
    @Throws(Exception::class)
    override fun run(args: ApplicationArguments?) {
        // 订阅WebSocket消息
        subscribeMessage { message: WebSocketMessageDto ->
            log.info { "WebSocket主题订阅收到消息session keys=${message.sessionKeys} message=${message.message}" }
            // 如果key不为空就按照key发消息 如果为空就群发
            if (CollUtil.isNotEmpty(message.sessionKeys)) {
                message.sessionKeys?.forEach { key: Long ->
                    if (WebSocketSessionHolder.existSession(key)) {
                        message.message?.let {
                            sendMessage(key, it)
                        }
                    }
                }
            } else {
                getSessionsAll().forEach { key: Long ->
                    message.message?.let {
                        sendMessage(key, it)
                    }
                }
            }
        }
        log.info { "初始化WebSocket主题订阅监听器成功" }
    }

    override fun getOrder(): Int {
        return -1
    }
}
